package popup

import android.graphics.Color
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.*
import app.AppContext
import com.hontech.pizzav2.R
import event.LoginChangedEvent
import manager.AppManager
import manager.AppTask
import manager.AsyncTask
import manager.NetworkManager
import org.greenrobot.eventbus.EventBus


class UserLoginWindow : Runnable {
    companion object {
        val Instance: UserLoginWindow by lazy { UserLoginWindow() }
        const val DEFAULT_ID = "lbx"
        const val DEFAULT_PASSWORD = "888888"
        var isShow = false
    }

    private val mView = LayoutInflater.from(AppContext).inflate(R.layout.popup_login, null)
    private val mEditTextId = mView.findViewById<EditText>(R.id.id_popup_login_id_edit_text)
    private val mImageViewId = mView.findViewById<ImageView>(R.id.id_popup_login_id_image_view)
    private val mEditTextPassword = mView.findViewById<EditText>(
        R.id.id_popup_login_password_edit_text
    )
    private val mImageViewPassword = mView.findViewById<ImageView>(
        R.id.id_popup_login_password_image_view
    )
    private val mButtonSetting = mView.findViewById<Button>(R.id.id_popup_login_setting_button)
    private val mButtonScan = mView.findViewById<Button>(R.id.id_popup_login_scan_button)
    private val mButtonInfo = mView.findViewById<Button>(R.id.id_popup_login_info_button)
    private val mLayout = mView.findViewById<LinearLayout>(R.id.id_popup_login_layout)

    private val mPopupWindow = PopupWindow(
        mView, WindowManager.LayoutParams.MATCH_PARENT,
        WindowManager.LayoutParams.MATCH_PARENT, true
    )

    private val mTitleText = mView.findViewById<TextView>(R.id.id_popup_login_text_title)

    init {
        initUi()
    }

    override fun run() {
        dismiss()
    }

    fun show(view: View) {
        if (isShow) {
            return
        }
        AppManager.isBusy = true
        isShow = true
        setUi()
        mPopupWindow.showAtLocation(view, Gravity.CENTER, 0, 0)
        AppTask.postDelayed(this, 120 * 1000)
    }

    private fun setUi() {
        mEditTextPassword.setText("")
        mEditTextId.setText("")
        mTitleText.textSize = 75f
        mTitleText.setTextColor(Color.WHITE)
        mTitleText.text = "Set up"
        mImageViewPassword.visibility = View.INVISIBLE
        mImageViewId.visibility = View.INVISIBLE
    }

    private fun setTitle(title: String) {
        mTitleText.textSize = 25f
        mTitleText.setTextColor(Color.RED)
        mTitleText.text = title
    }

    fun dismiss() {
        if (isShow) {
            AppTask.removeCallbacks(this)
            mPopupWindow.dismiss()
            AppManager.isBusy = false
            isShow = false
        }
    }

    private fun onClickSet(view: View) {
        val id = mEditTextId.text.toString()
        if (id.isEmpty()) {
            setTitle("Please input Username ")
            return
        }
        val pw = mEditTextPassword.text.toString()
        if (pw.isEmpty()) {
            setTitle("Please input Password")
            return
        }
        if ((id == DEFAULT_ID) && (pw == DEFAULT_PASSWORD)) {
            EventBus.getDefault().post(LoginChangedEvent(LoginChangedEvent.SET))
            return
        }
        AsyncTask.post {
            try {
                val ret = NetworkManager.checkIdAndPassword(id, pw)
                AppTask.post {
                    if (ret) {
                        EventBus.getDefault().post(LoginChangedEvent(LoginChangedEvent.SET))
                    } else {
                        setTitle("Wrong account or password")
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun onClickScan(view: View) {
        val id = mEditTextId.text.toString()
        if (id.isEmpty()) {
            setTitle("Please input Username ")
            return
        }
        val pw = mEditTextPassword.text.toString()
        if (pw.isEmpty()) {
            setTitle("Please input Password")
            return
        }
        if ((id == DEFAULT_ID) && (pw == DEFAULT_PASSWORD)) {
            EventBus.getDefault().post(LoginChangedEvent(LoginChangedEvent.SCAN))
            return
        }
        AsyncTask.post {
            val ret = NetworkManager.checkIdAndPassword(id, pw)
            AppTask.post {
                if (ret) {
                    EventBus.getDefault().post(LoginChangedEvent(LoginChangedEvent.SCAN))
                } else {
                    setTitle("Wrong account or password")
                }
            }
        }
    }

    private fun onClickInfo(view: View) {
        val id = mEditTextId.text.toString()
        if (id.isEmpty()) {
            setTitle("Please input Username ")
            return
        }
        val pw = mEditTextPassword.text.toString()
        if (pw.isEmpty()) {
            setTitle("Please input Password")
            return
        }
        if ((id == DEFAULT_ID) && (pw == DEFAULT_PASSWORD)) {
            EventBus.getDefault().post(LoginChangedEvent(LoginChangedEvent.INFO))
            return
        }
        AsyncTask.post {
            val ret = NetworkManager.checkIdAndPassword(id, pw)
            AppTask.post {
                if (ret) {
                    EventBus.getDefault().post(LoginChangedEvent(LoginChangedEvent.INFO))
                } else {
                    setTitle("Wrong account or password")
                }
            }
        }
    }

    private fun initUi() {
        mPopupWindow.isOutsideTouchable = true
        mLayout.setOnClickListener { }
        mView.setOnClickListener { dismiss() }
        mButtonSetting.setOnClickListener(::onClickSet)
        mButtonScan.setOnClickListener(::onClickScan)
        mButtonInfo.setOnClickListener(::onClickInfo)
        mImageViewId.setOnClickListener { mEditTextId.setText("") }
        mImageViewPassword.setOnClickListener { mEditTextPassword.setText("") }
        mEditTextPassword.addTextChangedListener(object : TextWatcher {

            override fun afterTextChanged(s: Editable) {
                if (s.isEmpty()) {
                    mImageViewPassword.visibility = View.INVISIBLE
                } else {
                    mImageViewPassword.visibility = View.VISIBLE
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        mEditTextId.addTextChangedListener(object : TextWatcher {

            override fun afterTextChanged(s: Editable) {
                if (s.isEmpty()) {
                    mImageViewId.visibility = View.INVISIBLE
                } else {
                    mImageViewId.visibility = View.VISIBLE
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
    }
}